package com.example.polarity;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class Joystick extends View {

	public Bitmap Jostick; 
	public float pivotX; 
	public float pivotY;
	public float angle;
	
	Matrix matrix;
	boolean rotated = false;
	
	float btnX;
	float btnY;
	
	public Joystick(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}
	
	public Joystick(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.setWillNotDraw(false);
		Jostick = BitmapFactory.decodeResource(getResources(), R.drawable.joystickbtn);
		pivotX = this.getWidth() /2;
		pivotY = this.getHeight() / 2;
		matrix = new Matrix();
		
		btnX = pivotX;
		btnY = pivotY;
	}
	
	public Joystick(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
		Jostick = BitmapFactory.decodeResource(getResources(), R.drawable.joystickbtn);
	}
	
	@Override
	protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) 
	{
		// TODO Auto-generated method stub
		Jostick =  Bitmap.createScaledBitmap(Jostick, 80, 80, false);
	}
	
	
	@Override
	public void onDraw(Canvas canvas)
	{
		
		matrix.setRotate(angle - 40);
		matrix.postTranslate(100 , 100);
		if(!rotated)
			canvas.drawBitmap(this.Jostick, this.getWidth() - 100, (this.getHeight() / 2) - 40, null );
		else
			canvas.drawBitmap(this.Jostick, matrix, null ); 
		
		invalidate();
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {

		btnY = event.getY();
		btnX = event.getX();
		if(event.getAction() == MotionEvent.ACTION_MOVE)
		{
			float deltaY = event.getY() - (pivotY + (this.getHeight() / 2));
			float deltaX = event.getX() - (pivotX + (this.getWidth() / 2));
			rotated = true;
			angle = (float) (Math.atan2(deltaY, deltaX) * 180 / Math.PI);
		}
		return true;
	}
	
}
